package org.acooly.secretbox.ui;

import java.util.ArrayList;
import java.util.List;

import org.acooly.android.utils.PasswordGenerator;
import org.acooly.android.utils.StringUtils;
import org.acooly.android.utils.ToastUtils;
import org.acooly.secretbox.Constants;
import org.acooly.secretbox.R;
import org.acooly.secretbox.common.BaseActivity;
import org.acooly.secretbox.service.AccountService;
import org.acooly.secretbox.service.AccountTypeService;
import org.acooly.secretbox.service.SettingService;
import org.acooly.secretbox.service.domain.Account;
import org.acooly.secretbox.service.domain.AccountType;
import org.acooly.secretbox.service.impl.AccountServiceImpl;
import org.acooly.secretbox.service.impl.AccountTypeServiceImpl;
import org.acooly.secretbox.service.impl.SettingServiceImpl;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.Spinner;

public class AccountActivity extends BaseActivity {

	private AccountService accountService;
	private SettingService settingService;
	private AccountTypeService accountTypeService;
	private ArrayAdapter<String> adapter;
	private Spinner spinner;

	/** 账户类型 */
	private List<String> accountTypes;

	private EditText viewAccountId;
	private EditText viewAccountName;
	private EditText viewUsername;
	private EditText viewComments;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account);
		accountService = new AccountServiceImpl(this);
		accountTypeService = new AccountTypeServiceImpl(this);
		settingService = new SettingServiceImpl(this);

		Button buttonSubmit = (Button) findViewById(R.id.account_submit_button);
		buttonSubmit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				save();
			}
		});
		Button buttonClose = (Button) findViewById(R.id.account_close_button);
		buttonClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		Button accountTypeAddButton = (Button) findViewById(R.id.account_type_add_button);
		accountTypeAddButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// showAddAccountTypeView();
				showCustomAialog();
			}
		});

		Button addNewPassword = (Button) findViewById(R.id.account_newpassword);
		addNewPassword.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showPasswordAialog();
			}
		});

		// 账户类型
		spinner = (Spinner) findViewById(R.id.account_accountType);
		accountTypes = getAccountTypes();
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, accountTypes);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		viewAccountId = (EditText) findViewById(R.id.account_id);
		viewAccountName = (EditText) findViewById(R.id.account_accountName);
		viewUsername = (EditText) findViewById(R.id.account_username);
		viewComments = (EditText) findViewById(R.id.account_comments);

		String id = getIntent().getStringExtra("id");
		if (StringUtils.isNotBlank(id)) {
			Account account = accountService.get(Integer.parseInt(id));
			viewAccountId.setText(String.valueOf(account.getId()));
			setTextView(R.id.account_accountName, account.getAccountName());
			viewUsername.setText(account.getUsername());
			setTextView(R.id.account_password, account.getPassword());
			spinner.setSelection(adapter.getPosition(account.getAccountType()));
			viewComments.setText(account.getComments());
		}
	}

	private List<String> getAccountTypes() {
		List<AccountType> accountTypes = accountTypeService.getAll();
		List<String> accountTypeNames = new ArrayList<String>();
		for (AccountType accountType : accountTypes) {
			accountTypeNames.add(accountType.getName());
		}
		return accountTypeNames;
	}

	private void save() {

		String id = getTextView(R.id.account_id);
		String accountName = getTextView(R.id.account_accountName);
		String username = getTextView(R.id.account_username);
		String password = getTextView(R.id.account_password);
		String accountType = adapter.getItem(spinner.getSelectedItemPosition());
		String comments = getTextView(R.id.account_comments);

		if (StringUtils.isBlank(accountName)) {
			ToastUtils.showShort(this, "账户标题不能为空");
			viewAccountName.setText("");
			viewAccountName.clearFocus();
			return;
		}
		if (StringUtils.isBlank(username)) {
			ToastUtils.showShort(this, "登录名不能为空");
			viewUsername.setText("");
			viewUsername.clearFocus();
			return;
		}
		// if (StringUtils.isBlank(password)) {
		// ToastUtils.showShort(this, "密码不能为空");
		// viewPassword.setText("");
		// viewPassword.clearFocus();
		// return;
		// }

		Account account = new Account(accountName, username, password, comments);
		if (StringUtils.isNotBlank(id)) {
			account.setId(Integer.parseInt(id));
		}
		account.setAccountType(accountType);

		try {
			accountService.save(account);
			setResult(RESULT_OK);
			finish();
		} catch (Exception e) {
			ToastUtils.showShort(this, e.getMessage());
		}
	}

	private void showCustomAialog() {

		final View view = getLayoutInflater().inflate(R.layout.account_type, null, false);
		final PopupWindow pw = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
		pw.setContentView(view);
		pw.setAnimationStyle(android.R.style.Animation_Dialog);
		pw.setFocusable(true);

		View parent = findViewById(R.id.account_type_add_button);
		pw.showAtLocation(parent, Gravity.CENTER, 0, 0);

		Button ok = (Button) view.findViewById(R.id.account_type_ok);
		ok.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				EditText editText = (EditText) view.findViewById(R.id.account_type_value);
				String value = editText.getText().toString();
				if (StringUtils.isBlank(value)) {
					ToastUtils.showLong(getApplicationContext(), "新类型不能为空");
					return;
				}

				if (adapter.getPosition(StringUtils.trimToEmpty(value)) < 0) {
					String oldValue = settingService.getValue(Constants.SETTING_ACCOUNT_TYPE);
					settingService.set(Constants.SETTING_ACCOUNT_TYPE, value + "," + oldValue);
					adapter.add(value);
					adapter.notifyDataSetChanged();
				}
				spinner.setSelection(adapter.getPosition(value));
				pw.dismiss();
			}
		});

		// 关闭alert对话框架
		Button cancel = (Button) view.findViewById(R.id.account_type_cancel);
		cancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				pw.dismiss();
			}
		});

	}

	private void showPasswordAialog() {
		final View view = getLayoutInflater().inflate(R.layout.password, null, false);
		final PopupWindow pw = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
		pw.setContentView(view);
		pw.setAnimationStyle(android.R.style.Animation_Toast);
		pw.setFocusable(true);
		View parent = findViewById(R.id.account_type_add_button);
		pw.showAtLocation(parent, Gravity.CENTER, 0, 0);
		Button passwordGenerator = (Button) view.findViewById(R.id.password_generator);
		passwordGenerator.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				CheckBox memberNumber = (CheckBox) view.findViewById(R.id.password_member_number);
				CheckBox memberLowercase = (CheckBox) view.findViewById(R.id.password_member_lowercase);
				CheckBox memberUppercase = (CheckBox) view.findViewById(R.id.password_member_uppercase);
				CheckBox memberSign = (CheckBox) view.findViewById(R.id.password_member_sign);

				int member = 0;
				if (memberNumber.isChecked()) {
					member += PasswordGenerator.MEMBER_NUMBER;
				}
				if (memberLowercase.isChecked()) {
					member += PasswordGenerator.MEMBER_LOWERCASE;
				}
				if (memberUppercase.isChecked()) {
					member += PasswordGenerator.MEMBER_UPPERCASE;
				}
				if (memberSign.isChecked()) {
					member += PasswordGenerator.MEMBER_SIGN;
				}

				if (member == 0) {
					ToastUtils.showShort(getApplicationContext(), "至少选择一种密码组成成员");
					return;
				}

				EditText pswdLength = (EditText) view.findViewById(R.id.password_length);
				String pswdLengthValue = pswdLength.getText().toString();
				if (StringUtils.isBlank(pswdLengthValue)) {
					ToastUtils.showShort(getApplicationContext(), "密码长度不能为空.");
					return;
				}

				int length = Integer.parseInt(pswdLengthValue);

				EditText passwordValue = (EditText) view.findViewById(R.id.password_value);
				String newPassword = PasswordGenerator.generater(length, member);
				passwordValue.setText(newPassword);
			}
		});

		Button passwordOk = (Button) view.findViewById(R.id.password_ok);
		passwordOk.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				EditText editText = (EditText) findViewById(R.id.account_password);
				EditText passwordValue = (EditText) view.findViewById(R.id.password_value);
				editText.setText(passwordValue.getText());
				pw.dismiss();
			}
		});

		// 关闭alert对话框架
		Button passwordCancel = (Button) view.findViewById(R.id.password_cancel);
		passwordCancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				pw.dismiss();
			}
		});
	}

}
